<?php
namespace app\common\service;

class PayPalIPNService
{
    // 验证 IPN 通知
    public function verifyIPN($rawPostData, $mode = 'sandbox')
    {
        // 确定验证端点（沙盒/生产环境）
        $endpoint = $mode === 'sandbox' 
            ? 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr'
            : 'https://ipnpb.paypal.com/cgi-bin/webscr';
        
        // 构建验证请求数据
        $verifyData = 'cmd=_notify-validate&' . $rawPostData;
        
        // 发送验证请求
        $ch = curl_init($endpoint);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $verifyData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Connection: Close',
            'User-Agent: Your Application Name'
        ]);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        // 检查错误
        if ($error) {
            throw new \Exception("CURL 错误: " . $error);
        }
        
        // 验证响应
        return trim($response) === 'VERIFIED';
    }
}
